import pandas as pd
from sklearn.feature_extraction import DictVectorizer
from sklearn.model_selection import train_test_split, GridSearchCV
from sklearn.tree import DecisionTreeClassifier
from sklearn.metrics import accuracy_score

def dtc_demo():
    # 1.加载数据源
    df = pd.read_csv("C:\\Users\\Administrator\\Desktop\\data\\tt\\train.csv")
    # 2. 数据清洗
    df["Age"].fillna(df["Age"].mean(), inplace=True)
    #  2.提取特征和目标
    X = df[["Pclass", "Sex", "Age"]]
    y = df["Survived"]
    # 创建DictVectorizer
    dict = DictVectorizer(sparse=False)
    X = dict.fit_transform(X.to_dict(orient="records"))

    x_train, x_test, y_train, y_test = train_test_split(X, y, test_size=0.3)
    print(dict.get_feature_names_out())
    print(X)

    # 3.创建模型
    # 设置网格搜索参数
    clf = DecisionTreeClassifier()
    param_grid = {'max_depth': [1, 3, 5, 7, 9],"random_state":[33,44]}
    # 初始化网格搜索对象
    clf = GridSearchCV(estimator=clf, param_grid=param_grid, cv=5)
    clf.fit(x_train, y_train)
    # 4. 预测
    y_pred = clf.predict(x_test)

    # 5.模型评估
    print(accuracy_score(y_test, y_pred))

    best_params = clf.best_params_
    best_model = clf.best_estimator_
    print(best_params)


if __name__ == '__main__':
    dtc_demo()
